package Servlet;

import db.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

public class RegisterServlet extends HttpServlet {
    public RegisterServlet() {
        super();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String account = request.getParameter("account"); // 从 request 中获取名为 account 的参数的值
        String password = request.getParameter("password"); // 从 request 中获取名为 password 的参数的值

        String Code = "";

        try {
            Connection connect = DBUtil.getConnect();
            Statement statement = connect.createStatement(); // Statement可以理解为数据库操作实例，对数据库的所有操作都通过它来实现
            ResultSet result;

            String sqlQuery = "select * from user_account where username='" + account + "'";

            // 查询类操作返回一个ResultSet集合，没有查到结果时ResultSet的长度为0
            result = statement.executeQuery(sqlQuery); // 先查询同样的账号（比如手机号）是否存在
            if(result.next()){ // 已存在
                Code = "-3";
            } else { // 不存在
                String sqlInsertPass = "insert into " + DBUtil.TABLE_USER_ACCOUNT + " (username,password) values('"+account+"','"+password+"')";
                int row1 = statement.executeUpdate(sqlInsertPass); // 插入帐号密码
                if(row1 == 1){
                        Code = "0";
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("Code", Code);

        response.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
        PrintWriter pw = response.getWriter(); // 获取 response 的输出流
        pw.println(map.toString()); // 通过输出流把业务逻辑的结果输出
        pw.flush();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
